import { useRef } from 'react'
import ImageClip from './ImageClip'
import './scss/ImageSelect.scss'
import AddSvg from '@/svg/AddSvg'
interface Props {
  value: string
  onChange: (value: string) => void
  /**
   * 图片裁剪比例
   */
  clipAspect: number

  width?: number
}
/**
 * 图片选择器
 * @returns
 */
const ImageSelect = (props: Props) => {
  const imageClipRef = useRef(null)
  const imageInputRef = useRef(null)
  async function onFileChange(e: React.ChangeEvent<HTMLInputElement>) {
    if (e.target.files && e.target.files.length > 0) {
      const tmpUrl = URL.createObjectURL(e.target.files[0])
      const result = await imageClipRef.current.show({
        imageUrl: tmpUrl,
        clipProportion: {
          width: 1,
          height: props.clipAspect,
        },
      })
      console.log(result.imageUrl)

      props.onChange(result.imageUrl)
    }
  }
  return (
    <div
      className="ImageSelectComponent"
      style={{
        aspectRatio: 1 / props.clipAspect,
        width: props.width,
      }}>
      <input
        ref={imageInputRef}
        type="file"
        accept="image/*"
        style={{
          display: 'none',
        }}
        onChange={onFileChange}
      />
      {!props.value && (
        <div
          className="empty"
          onClick={() => {
            imageInputRef.current.click()
          }}>
          <AddSvg />
          <span>点击上传图片</span>
        </div>
      )}
      {props.value && (
        <div
          className="image-box"
          onClick={() => {
            imageInputRef.current.click()
          }}>
          <img className="img" src={props.value} />
          <div className="repupload">重新上传</div>
        </div>
      )}

      <ImageClip ref={imageClipRef} />
    </div>
  )
}

export default ImageSelect
